#!/bin/bash
# Cheating here...
# $Id: autogen.sh 33 2012-03-30 18:11:16Z dubkat $

SUBDIRS="$(pwd) libraries/libpcre libraries/libconfig libraries/libratbox libraries/sqlite"


run()
{
    echo
    echo "***************************************"
    echo " running in $(pwd): $*"
    echo "***************************************"
    eval $*
    save=$?
    if [ $save -gt 0 ]; then
        echo "***************************************************************"
        echo "Died with exit code '${save}' while running $*"
        echo "***************************************************************"
   fi
   return $save;
}

apply_patches()
{
    for x in $(ls patches/*.patch); do
        echo "Applying Patch: $x"
        patch -p0 -f --dry-run < $x >/dev/null
        save=$?
        if [ $save -eq 0 ]; then
        	patch -p0 < $x
        else
            echo "Patch $x FAILED.... Probably already patched... skipping"
        fi
    done
}

check_autotools_version()
{
    ret=0
    if [ ! -x `which aclocal-1.11` ]; then
        echo "Error: We need aclocal-1.11. Please install automake-1.11"
        ret=1
    fi
    if [ ! -x `which automake-1.11` ]; then
        echo "Error: We need automake-1.11. Please install automake-1.11"
        ret=1
    fi
    if [ $ret == 1 ]; then
        exit 1;
    fi
}

echo
echo
echo "This script is about to build/rebuild the Makefiles and configure scripts to build ratbox-monitor."
echo "It will likely be loud and dump tons of warnings, most of which you can ignore, unless it fails."
echo
sleep 2

# c-ares needs aclocal-1.10 and automake-1.10
#check_autotools_version

apply_patches

for d in $SUBDIRS; do
    pushd $d
    run libtoolize --copy --force
    r=$(run aclocal -I m4)
    if [ "$r" != "0" ]; then
        run aclocal
    fi
    run autoheader
    run automake -ac
    run autoconf
    #run autoreconf -i -v
    popd
done

exit 0
